//
//  RxLearningVC.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/5/6.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import CooperSwift

class RxPerson : NSObject {
    @objc dynamic var name = "name0"
}

class RxLearningAVC: UIViewController {
    
    let disposeBag = DisposeBag()
    
    lazy var btn: UIButton = {
        var button = UIButton.init()
        button.setTitle("Test Rx Button", for: .normal)
        button.backgroundColor = .random()
        return button
    }()
    
    lazy var field: UITextField = {
        var button = UITextField.init()
        button.backgroundColor = .random()
        return button
    }()

    
    lazy var label: UILabel = {
        var label = UILabel.init()
        label.backgroundColor = .random()
        label.text = "xxxx"
        return label
    }()
    
    var timer: Observable<Int>?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        view.addSubviews([btn, field, label])
        
        // button
        btn.snp.makeConstraints { make in
            make.top.equalTo(view).offset((Screen.statusBarHeight + Screen.navBarHeight + 20))
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(44)
        }
        
        let btnTimer = Observable<Int>.interval(.milliseconds(1), scheduler: MainScheduler.instance)
        btnTimer.map(formatTimeInterval).bind(to: btn.rx.attributedTitle()).disposed(by: disposeBag)
//        btn.rx.title(for: .normal).
        
        btn.rx.tap.asObservable().subscribe { _ in
            debugPrint("btn rx tap")
        }.disposed(by: disposeBag)
        
        
        btn.rx.controlEvent(.touchDownRepeat).subscribe { _ in
            debugPrint("btn rx touchDownRepeat")
        }.disposed(by: disposeBag)
        
        
        // field
        field.snp.makeConstraints { make in
            make.top.equalTo(btn.snp_bottomMargin).offset(20)
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(44)
        }
        
        field.rx.text.asObservable().filter({ $0!.count > 0 }).subscribe(onNext: { text in
            debugPrint("field rx \(String(describing: text))")
        }).disposed(by: disposeBag)
        
        
        // KVO
        let p = RxPerson()
        p.rx.observeWeakly(String.self, "name").subscribe(onNext: { (change) in
            debugPrint("person name change \(String(describing: change))")
        }).disposed(by: disposeBag)
        p.name = "张三"
        p.name = "李四"
        
        
        // notice
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).subscribe { (event) in
            debugPrint("notification \(event)")
        }.disposed(by: disposeBag)

        label.snp.makeConstraints { make in
            make.top.equalTo(field.snp_bottomMargin).offset(20)
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(44)
        }
        
        let tap = UITapGestureRecognizer.init()
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(tap)
        tap.rx.event.subscribe { (gesture) in
            print(gesture)
        }.disposed(by: disposeBag)
        
        timer = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
        timer?.asObservable().subscribe(onNext: { idx in
            print("timer \(idx)")
        }).disposed(by: disposeBag)
        
        // Do any additional setup after loading the view.
    }
    
    //将数字转成对应的富文本
    func formatTimeInterval(ms: NSInteger) -> NSMutableAttributedString {
        let string = String(format: "%0.2d:%0.2d.%0.2d",
                            arguments: [(ms / 600) % 600, (ms % 600 ) / 10, ms % 10])
        //富文本设置
        let attributeString = NSMutableAttributedString(string: string)
        //从文本0开始6个字符字体HelveticaNeue-Bold,16号
        attributeString.addAttribute(NSAttributedString.Key.font,
                                     value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,
                                     range: NSMakeRange(0, 5))
        //设置字体颜色
        attributeString.addAttribute(NSAttributedString.Key.foregroundColor,
                                     value: UIColor.white, range: NSMakeRange(0, 5))
        //设置文字背景颜色
        attributeString.addAttribute(NSAttributedString.Key.backgroundColor,
                                     value: UIColor.orange, range: NSMakeRange(0, 5))
        return attributeString
    }
    
    deinit {
        print("rx learning one")
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
